#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import re

from wingman import logger
from wingman.common.error import ErrorCode
from config.rules_sql_mysql import *
from config.rules_filter import *
from config.system import RECORD_DATABASE
from .database.mysql import CustomMysql


class DBMap:

    def __init__(self):
        """检查是否要写入数据库"""
        if not RECORD_DATABASE:
            return

    def __get_filtered(self, message, function_name):
        """检查是否包含需要过滤的内容"""
        is_filtered = False
        filter_rules = globals()[function_name + "_filtered_keys"]
        for rule in filter_rules:
            pattern = re.compile(rule)  # 将规则编译为正则表达式
            for key, value in message.items():
                if pattern.search(str(value)):  # 使用search方法进行匹配
                    is_filtered = True
                    break
            if is_filtered:
                break
        return is_filtered

    def get_enter(self, message, function_name, env_name):
        if not RECORD_DATABASE:
            return
        """数据入库分发"""
        # logger.debug(ErrorCode.DEBUG.value, function_name, __name__)

        # 根据标志判断是否写入
        if self.__get_filtered(message, function_name):
            logger.warning(ErrorCode.GETMYSQL.value,
                           "db Message contains filtered content, will not send.",
                           __name__)
        else:
            if "test_" in function_name:
                function_name = "get_inspection_assertion_exception"
            # 获取SQL语句和数据
            sql_info = sql_mappings[function_name]
            insert_query = sql_info['insert_query']
            data = sql_info['data_func'](message)

            try:
                CustomMysql().get_modify(insert_query, data, env_name)
            except Exception as e:
                logger.error(ErrorCode.CALLDB_GETMYSQL.value, str(e), __name__)
        # return result

    def get_query(self, message, function_name=False, env_name="local"):
        """数据query分发"""
        try:
            result = CustomMysql().get_modify(message, function_name, env_name)
        except Exception as e:
            logger.error(ErrorCode.CALLDB_GETMYSQL.value, str(e), __name__)
            result = str(e)  # 这里可以保留原来的赋值
        return result
